package com.dianban.controller;

import com.dianban.base.ResultVo;
import com.dianban.entity.FacePayStoreConsumeLog;
import com.dianban.entity.FacePayStoreOrder;
import com.dianban.entity.FacePayStoreOrderShareLog;
import com.dianban.service.FacePayStoreConsumeLogService;
import com.dianban.service.FacePayStoreOrderService;
import com.dianban.service.FacePayStoreOrderShareLogService;
import com.dianban.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 每天23:50分执行一次
 */
@Api(value = "ApiSyncStoreOrderController", description = "同步门店老板399订单数据处理每天自动核销控制器")
@RestController
@RequestMapping(value = "${interfacePath}/syncStoreOrder/")
public class ApiSyncStoreOrderController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiSyncStoreOrderController.class);

    @Autowired
    private FacePayStoreOrderService facePayStoreOrderService;
    @Autowired
    private FacePayStoreConsumeLogService facePayStoreConsumeLogService;
    @Autowired
    private FacePayStoreOrderShareLogService facePayStoreOrderShareLogService;

    @ApiOperation(notes = "dealOrder", httpMethod = "GET", value = "同步门店老板399订单数据处理每天自动核销状态相关值")
    @RequestMapping(value = "dealOrder", method = RequestMethod.GET)
    public ResultVo dealOrder(HttpServletRequest request, HttpServletResponse response) {
        logger.info("同步门店老板399订单数据处理线下核销状态相关值,开始");
        try {
            List<FacePayStoreOrder> facePayStoreOrders = facePayStoreOrderService.findByParams(DateUtils.generateMonthDayBegin(), DateUtils.generateMonthDayEnd(), null, null, "20", "20", "399");
            if (!CollectionUtils.isEmpty(facePayStoreOrders)) {
                for (FacePayStoreOrder facePayStoreOrder : facePayStoreOrders) {
                    // 判断今天有没399的核销
                    List<FacePayStoreConsumeLog> facePayStoreConsumeLogs = facePayStoreConsumeLogService.findByParams(DateUtils.generateDayBegin(), DateUtils.generateDayEnd(), facePayStoreOrder.getUserId(), facePayStoreOrder.getId());
                    if (CollectionUtils.isEmpty(facePayStoreConsumeLogs)) {
                        facePayStoreOrder.setHasVerifyCount(facePayStoreOrder.getHasVerifyCount() + 1);
                        // 更新记录
                        facePayStoreOrderService.updateVerify(facePayStoreOrder.getId(), facePayStoreOrder.getHasVerifyCount(), null);
                        // 插入记录
                        FacePayStoreConsumeLog facePayStoreConsumeLog = new FacePayStoreConsumeLog();
                        facePayStoreConsumeLog.setStoreId(facePayStoreOrder.getStoreId());
                        facePayStoreConsumeLog.setUserId(facePayStoreOrder.getUserId());
                        BigDecimal money = facePayStoreOrder.getMoney();
                        facePayStoreConsumeLog.setMoney(money);
                        facePayStoreConsumeLog.setType("50");
                        facePayStoreConsumeLog.setOfflineOrderId(facePayStoreOrder.getId());
                        facePayStoreConsumeLog.setMemo("线下" + money + "体验套餐核销-系统回收自动核销");
                        facePayStoreConsumeLogService.insert(facePayStoreConsumeLog);
                    }
                }
            }
        } catch (Throwable e) {
            logger.error("同步门店老板399订单数据处理线下核销状态相关值,异常:{}", e.getMessage());
            e.printStackTrace();
        }
        logger.info("同步门店老板399订单数据处理线下核销状态相关值,完成");
        return ResultVo.success("", "操作成功");
    }

    // 2999元/30次（使用时间：限120天内使用完毕，到期清零）
    @ApiOperation(notes = "deal2999Order", httpMethod = "GET", value = "同步2999/30次限120天内使用完毕,到期清零自动核销状态相关值")
    @RequestMapping(value = "deal2999Order", method = RequestMethod.GET)
    public ResultVo deal2999Order(HttpServletRequest request, HttpServletResponse response) {
        logger.info("同步2999/30次限120天内使用完毕,到期清零自动核销状态相关值,开始");
        try {
            List<FacePayStoreOrder> facePayStoreOrders = facePayStoreOrderService.findByParams(null, null, null, null, "20", "20", "2999");
            if (!CollectionUtils.isEmpty(facePayStoreOrders)) {
                for (FacePayStoreOrder facePayStoreOrder : facePayStoreOrders) {
                    if (facePayStoreOrder.getHasVerifyCount() != null && facePayStoreOrder.getHasVerifyCount() != 30) {
                        // 判断购买时间有没超过120天
                        Long createtime = facePayStoreOrder.getCreatetime();
                        int diff = DateUtils.differDay(new Date(), new Date(createtime * 1000));
                        if (diff > 120) {
                            facePayStoreOrder.setHasVerifyCount(30);
                            // 更新记录
                            facePayStoreOrderService.updateVerify(facePayStoreOrder.getId(), facePayStoreOrder.getHasVerifyCount(), null);
                            // 插入记录
                            FacePayStoreConsumeLog facePayStoreConsumeLog = new FacePayStoreConsumeLog();
                            facePayStoreConsumeLog.setStoreId(facePayStoreOrder.getStoreId());
                            facePayStoreConsumeLog.setUserId(facePayStoreOrder.getUserId());
                            BigDecimal money = facePayStoreOrder.getMoney();
                            facePayStoreConsumeLog.setMoney(money);
                            facePayStoreConsumeLog.setType("50");
                            facePayStoreConsumeLog.setOfflineOrderId(facePayStoreOrder.getId());
                            facePayStoreConsumeLog.setMemo("线下" + money + "套餐核销-超过120天系统回收自动核销");
                            facePayStoreConsumeLogService.insert(facePayStoreConsumeLog);
                        }
                    }
                }
            }
        } catch (Throwable e) {
            logger.error("同步2999/30次限120天内使用完毕,到期清零自动核销状态相关值,异常:{}", e.getMessage());
            e.printStackTrace();
        }
        logger.info("同步2999/30次限120天内使用完毕,到期清零自动核销状态相关值,完成");
        return ResultVo.success("", "操作成功");
    }

    // 3000元/30次/20次（使用时间：限150天内使用完毕，到期清零）
    @ApiOperation(notes = "deal3000Order", httpMethod = "GET", value = "同步3000/30次/20次限150天内使用完毕,到期清零自动核销状态相关值")
    @RequestMapping(value = "deal3000Order", method = RequestMethod.GET)
    public ResultVo deal3000Order(HttpServletRequest request, HttpServletResponse response) {
        logger.info("同步3000/30次/20次限150天内使用完毕,到期清零自动核销状态相关值,开始");
        try {
            List<FacePayStoreOrder> facePayStoreOrders = facePayStoreOrderService.findByParams(null, null, null, null, "20", "20", "3000");
            if (!CollectionUtils.isEmpty(facePayStoreOrders)) {
                for (FacePayStoreOrder facePayStoreOrder : facePayStoreOrders) {
                    if (facePayStoreOrder.getHasVerifyCount() != null && facePayStoreOrder.getHasVerifyCount() != facePayStoreOrder.getCanVerifyCount()) {
                        // 判断购买时间有没超过150天
                        Long createtime = facePayStoreOrder.getCreatetime();
                        int diff = DateUtils.differDay(new Date(), new Date(createtime * 1000));
                        if (diff > 150) {
                            facePayStoreOrder.setHasVerifyCount(facePayStoreOrder.getCanVerifyCount());
                            // 更新记录
                            facePayStoreOrderService.updateVerify(facePayStoreOrder.getId(), facePayStoreOrder.getHasVerifyCount(), null);
                            // 插入记录
                            FacePayStoreConsumeLog facePayStoreConsumeLog = new FacePayStoreConsumeLog();
                            facePayStoreConsumeLog.setStoreId(facePayStoreOrder.getStoreId());
                            facePayStoreConsumeLog.setUserId(facePayStoreOrder.getUserId());
                            BigDecimal money = facePayStoreOrder.getMoney();
                            facePayStoreConsumeLog.setMoney(money);
                            facePayStoreConsumeLog.setType("50");
                            facePayStoreConsumeLog.setOfflineOrderId(facePayStoreOrder.getId());
                            facePayStoreConsumeLog.setMemo("线下" + money + "套餐核销-超过150天系统回收自动核销");
                            facePayStoreConsumeLogService.insert(facePayStoreConsumeLog);
                        }
                    }
                }
            }
        } catch (Throwable e) {
            logger.error("同步3000/30次/20次限150天内使用完毕,到期清零自动核销状态相关值,异常:{}", e.getMessage());
            e.printStackTrace();
        }
        logger.info("同步3000/30次/20次限150天内使用完毕,到期清零自动核销状态相关值,完成");
        return ResultVo.success("", "操作成功");
    }

    // 1999元/15次（使用时间：限90天内使用完毕，到期清零）
    @ApiOperation(notes = "deal1999Order", httpMethod = "GET", value = "同步1999/15次限90天内使用完毕,到期清零自动核销状态相关值")
    @RequestMapping(value = "deal1999Order", method = RequestMethod.GET)
    public ResultVo deal1999Order(HttpServletRequest request, HttpServletResponse response) {
        logger.info("同步1999/15次限90天内使用完毕,到期清零自动核销状态相关值,开始");
        try {
            List<FacePayStoreOrder> facePayStoreOrders = facePayStoreOrderService.findByParams(null, null, null, null, "20", "20", "1999");
            if (!CollectionUtils.isEmpty(facePayStoreOrders)) {
                for (FacePayStoreOrder facePayStoreOrder : facePayStoreOrders) {
                    if (facePayStoreOrder.getHasVerifyCount() != null && facePayStoreOrder.getHasVerifyCount() != facePayStoreOrder.getCanVerifyCount()) {
                        List<FacePayStoreConsumeLog> list = facePayStoreConsumeLogService.findList(null, facePayStoreOrder.getStoreId(), null);
                        // 以设备第一次开机使用之后7天为界限
                        if (!CollectionUtils.isEmpty(list)) {
                            // 最早的一条
                            FacePayStoreConsumeLog facePayStoreConsumeLog1 = list.get(0);
                            // 判断购买时间有没超过90天
                            Long createtime = facePayStoreOrder.getCreatetime();
                            if (facePayStoreConsumeLog1.getCreatetime() > createtime) {
                                createtime = facePayStoreConsumeLog1.getCreatetime();
                            }
                            int diff = DateUtils.differDay(new Date(), new Date(createtime * 1000));
                            if (diff > 90) {
                                facePayStoreOrder.setHasVerifyCount(facePayStoreOrder.getCanVerifyCount());
                                // 更新记录
                                facePayStoreOrderService.updateVerify(facePayStoreOrder.getId(), facePayStoreOrder.getHasVerifyCount(), null);
                                // 插入记录
                                FacePayStoreConsumeLog facePayStoreConsumeLog = new FacePayStoreConsumeLog();
                                facePayStoreConsumeLog.setStoreId(facePayStoreOrder.getStoreId());
                                facePayStoreConsumeLog.setUserId(facePayStoreOrder.getUserId());
                                BigDecimal money = facePayStoreOrder.getMoney();
                                facePayStoreConsumeLog.setMoney(money);
                                facePayStoreConsumeLog.setType("50");
                                facePayStoreConsumeLog.setOfflineOrderId(facePayStoreOrder.getId());
                                facePayStoreConsumeLog.setMemo("线下" + money + "套餐核销-超过90天系统回收自动核销");
                                facePayStoreConsumeLogService.insert(facePayStoreConsumeLog);
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
            logger.error("同步1999/15次限90天内使用完毕,到期清零自动核销状态相关值,异常:{}", e.getMessage());
            e.printStackTrace();
        }
        logger.info("同步1999/15次限90天内使用完毕,到期清零自动核销状态相关值,完成");
        return ResultVo.success("", "操作成功");
    }

    // 2998元/20次（使用时间：限60天内使用完毕，到期清零）
    @ApiOperation(notes = "deal2998Order", httpMethod = "GET", value = "同步2998/20次限60天内使用完毕,到期清零自动核销状态相关值")
    @RequestMapping(value = "deal2998Order", method = RequestMethod.GET)
    public ResultVo deal2998Order(HttpServletRequest request, HttpServletResponse response) {
        logger.info("同步2998/20次限60天内使用完毕,到期清零自动核销状态相关值,开始");
        try {
            List<FacePayStoreOrder> facePayStoreOrders = facePayStoreOrderService.findByParams(null, null, null, null, "20", "20", "2998");
            if (!CollectionUtils.isEmpty(facePayStoreOrders)) {
                for (FacePayStoreOrder facePayStoreOrder : facePayStoreOrders) {
                    if (facePayStoreOrder.getHasVerifyCount() != null && facePayStoreOrder.getHasVerifyCount() != facePayStoreOrder.getCanVerifyCount()) {
                        // 判断购买时间有没超过60天
                        Long createtime = facePayStoreOrder.getCreatetime();
                        int diff = DateUtils.differDay(new Date(), new Date(createtime * 1000));
                        if (diff > 60) {
                            facePayStoreOrder.setHasVerifyCount(facePayStoreOrder.getCanVerifyCount());
                            // 更新记录
                            facePayStoreOrderService.updateVerify(facePayStoreOrder.getId(), facePayStoreOrder.getHasVerifyCount(), null);
                            // 插入记录
                            FacePayStoreConsumeLog facePayStoreConsumeLog = new FacePayStoreConsumeLog();
                            facePayStoreConsumeLog.setStoreId(facePayStoreOrder.getStoreId());
                            facePayStoreConsumeLog.setUserId(facePayStoreOrder.getUserId());
                            BigDecimal money = facePayStoreOrder.getMoney();
                            facePayStoreConsumeLog.setMoney(money);
                            facePayStoreConsumeLog.setType("50");
                            facePayStoreConsumeLog.setOfflineOrderId(facePayStoreOrder.getId());
                            facePayStoreConsumeLog.setMemo("线下" + money + "套餐核销-超过60天系统回收自动核销");
                            facePayStoreConsumeLogService.insert(facePayStoreConsumeLog);
                        }
                    }
                }
            }
        } catch (Throwable e) {
            logger.error("同步2998/20次限60天内使用完毕,到期清零自动核销状态相关值,异常:{}", e.getMessage());
            e.printStackTrace();
        }
        logger.info("同步2998/20次限60天内使用完毕,到期清零自动核销状态相关值,完成");
        return ResultVo.success("", "操作成功");
    }

    // 回收订单分享能量舱失效次数每小时一次,定时任务,处理失效的
    @ApiOperation(notes = "dealShareLog", httpMethod = "GET", value = "回收订单分享能量舱失效次数每小时一次")
    @RequestMapping(value = "dealShareLog", method = RequestMethod.GET)
    public ResultVo dealShareLog(HttpServletRequest request, HttpServletResponse response) {
        logger.info("回收订单分享能量舱失效次数每小时一次");
        try {
            List<FacePayStoreOrderShareLog> list = facePayStoreOrderShareLogService.findList("0", null, null);
            if (!CollectionUtils.isEmpty(list)) {
                for (FacePayStoreOrderShareLog shareLog : list) {
                    Date createTime = new Date(shareLog.getCreatetime() * 1000);
                    Date effectTimeEnd = DateUtils.addDays(createTime, 1);
                    // 判断下是否已过有效期
                    if (DateUtils.format(effectTimeEnd, DateUtils.Y_M_D_H_M_S).compareTo(DateUtils.formatNow(DateUtils.Y_M_D_H_M_S)) < 0) {
                        if (!"3".equals(shareLog.getStatus())) {
                            facePayStoreOrderShareLogService.update(shareLog.getId(), "3", null, null);
                            // 返回次数
                            FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findById(shareLog.getOrderId());
                            if (facePayStoreOrder != null) {
                                facePayStoreOrder.setSharingCount(facePayStoreOrder.getSharingCount() - 1);
                                facePayStoreOrder.setCanVerifyCount(facePayStoreOrder.getCanVerifyCount() + 1);
                                facePayStoreOrderService.update(facePayStoreOrder);
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
            logger.error("回收订单分享能量舱失效次数每小时一次,异常:{}", e.getMessage());
            e.printStackTrace();
        }
        logger.info("回收订单分享能量舱失效次数每小时一次,完成");
        return ResultVo.success("", "操作成功");
    }
}
